package com.lg.cms.config;

import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @Description: swagger3配置类
 * @Url: localhost:port/swagger-ui/#/
 * @Author: wuyuhang
 * @create: 2020-09-21 20:46
 */
@Configuration
@EnableOpenApi
@Slf4j
public class Swagger3Config implements WebMvcConfigurer {

    /**
     * 获取使用环境,
     */
    @Value("${spring.profiles.active}")
    private String active;

    private Boolean enable = false;

    @Bean
    public Docket createRestApi() {
        // 判断使用环境是否为开发环境dev, 如果是开启swagger3
        if(active.equals("dev")){
            log.info("swagger3:开发环境, 开启api");
            enable = true;
        }else{
            log.info("swagger3:其他环境, 未开启api");
        }
        return new Docket(DocumentationType.OAS_30).pathMapping("/")
                .enable(enable)
                .apiInfo(this.apiInfo())
                .select() // 指定需要发布到Swagger的接口目录，不支持通配符
                .apis(RequestHandlerSelectors.basePackage("com.lg.cms"))
                .paths(PathSelectors.any())
                .build()
                // 支持的通讯协议集合
                .protocols(this.newHashSet("https", "http"));
    }

    @SafeVarargs
    private final <T> Set<T> newHashSet(T... ts) {
        if (ts.length > 0) {
            return new LinkedHashSet<>(Arrays.asList(ts));
        }
        return null;
    }

    private ApiInfo apiInfo() {

        return new ApiInfoBuilder().title("Swagger Api Doc")
                .description("SpringBoot后台接口")
                .contact(new Contact("user", null, "xyz@qq.com"))
                .version("Application Version: 1.0.0")
                .build();

    }
}